package cn.aloxc.tianya.reader;

import java.io.InputStream;
import java.net.URL;
import javax.xml.parsers.*;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import cn.aloxc.tools.RSSFeed;
import cn.aloxc.tools.RSSHandler;
import cn.aloxc.tools.RSSItem;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class Activity_test_Xmllist extends Activity implements
		OnItemClickListener{

	public final String RSS_URL = "http://blog.s135.com/feed.php";
	public final String tag = "RSSReader";
	private RSSFeed feed = null;
	private InputStream inStream;

	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.activity_test_xmllist);
		feed = getFeed(RSS_URL);
		showListView();
	}
	private RSSFeed getFeed(String urlString) {
		try {
			URL url = new URL(urlString);
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			XMLReader xmlreader = parser.getXMLReader();
			RSSHandler rssHandler = new RSSHandler();
			xmlreader.setContentHandler(rssHandler);
			inStream = url.openStream();
			InputSource is = new InputSource(inStream);
			xmlreader.parse(is);
			return rssHandler.getFeed();
		} catch (Exception ee) {
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	private void showListView( ) {
		ListView itemlist = (ListView) findViewById(R.id.test_xmllist_content_rssList);
		if (feed == null) {
			setTitle("无效的Rss！");
			return;
		}
		SimpleAdapter adapter = new SimpleAdapter(this, feed
				.getAllItemsForListView(), android.R.layout.simple_list_item_2,
				new String[] { RSSItem.TITLE, RSSItem.PUBDATE,
						RSSItem.CATEGORY, RSSItem.DESCRIPTION, RSSItem.LINK },
				new int[] { android.R.id.text1, android.R.id.text2,
						android.R.id.button1, android.R.id.button2,
						android.R.id.button3 });
		itemlist.setAdapter(adapter);
		itemlist.setOnItemClickListener(this);
		itemlist.setSelection(0);

	}

	@SuppressWarnings("unchecked")
	public void onItemClick(AdapterView parent, View v, int position, long id) {
		Intent itemintent = new Intent(this,
				Activity_test_xmllist_content.class);
		Bundle b = new Bundle();
		b.putString("title", feed.getItem(position).getTitle());
		b.putString("description", feed.getItem(position).getDescription());
		b.putString("link", feed.getItem(position).getLink());
		b.putString("pubdate", feed.getItem(position).getPubDate());
		b.putString("category", feed.getItem(position).getCategory());
		itemintent.putExtra("android.intent.extra.rssItem", b);
		startActivityForResult(itemintent, 0);
	}
}
